package gfxTest;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


@SuppressWarnings("serial")
public class MainPanel extends JPanel implements MouseListener {		//implements Mouse {
	 
	//Variablen-Deklaration
	double ballx=0.0, bally=0.0;
    Ball ball = new Ball((int)ballx,(int)bally);
    BBall[] balls = new BBall[50];	//private
    int ballcounter=0;
    int ballcreator=0;
	
    
    //Konstruktor
	public MainPanel(int wid, int hig) {
		super();
		setSize(wid,hig);
		this.addMouseListener(this);
		this.setDoubleBuffered(true);
	}
	
	public void run() {
		while(true) {
			
			for(int i=0;i<ballcounter;i++) {
				balls[i].bounce();
			}
			
			repaint();
			
			try {
				wait(2);
			} catch(Exception e) {}
		}
	}

	//Zeichnen-Methode
	public void paint(Graphics gfx) {
		super.paint(gfx);
		Graphics2D g = (Graphics2D)gfx;
		
		try {
			ballx = (double)getMousePosition().x;
			bally = (double)getMousePosition().y;
		
			if(ballx < ball.rad)
				ballx = ball.rad;
			if(ballx > MainFrame.WIDTH-ball.rad)
				ballx = MainFrame.WIDTH-ball.rad;
			if(bally < ball.rad)
				bally = ball.rad;
			if(bally > MainFrame.HEIGHT-2*ball.rad)
				bally = MainFrame.HEIGHT-2*ball.rad;
			
			ball.move((int)ballx,(int)bally);
			//g.setColor(Color.BLACK);
			ball.draw(g);
			g.drawString(ballx+ " " +bally, 20, 20);
	
		}
		catch(NullPointerException npe) {
			
		}
		finally{
	
			for(int i=0;i<ballcounter;i++) {
				g.setColor(balls[i].color);
				for(int j=0;j<ballcounter;j++) {
					if(i!=j)
					balls[i].collides(balls[j]);	
				}
			balls[i].draw(g);
			}

		}
	}

	
	/*
	 * implement MouseListener methods
	 */
	
	@Override
	public void mouseClicked(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mousePressed(MouseEvent e) {
		if(e.getButton() == MouseEvent.BUTTON1) {
			balls[ballcreator]=new BBall((int)ballx,(int)bally);
			balls[ballcreator].color=new Color((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255));
			ballcreator++;
			
			if(ballcreator>=balls.length-1) {
				ballcreator=0;
			}
			else if(!(ballcounter>=balls.length-1))
				ballcounter++;
		} else if(e.getButton() == MouseEvent.BUTTON3) {
			ballcreator=0;
			ballcounter=0;
		}
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

}
